<template>
  <div class="Hcont" v-if="homepage === 3">
    <!-- 头部导航 -->
    <div class="Hhead" @click="toHcont">
      <div class="hd1">
        <img src="../assets/logo3.png" alt="系统logo" class="hd11">
        <div class="hd12 noselect">
          <div class="hd121">智能配送</div>
          <div class="hd122">Intelligent Distribution</div>
        </div>
      </div>
      <img src="../assets/work.png" alt="工作图标" class="hd2">
      <div class="hd4"></div>
      <div class="hd3">
        <img src="../assets/tou.png" alt="用户头像" class="hd31">
        <el-dropdown>
          <span class="el-dropdown-link noselect xiaoshou" @click.stop>
            Qin<el-icon class="el-icon--right"><ArrowDown /></el-icon>
        </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item :icon="Postcard">个人信息</el-dropdown-item>
              <el-dropdown-item :icon="User" @click="customer">AI客服</el-dropdown-item>
              <el-dropdown-item :icon="Setting">设置</el-dropdown-item>
              <el-dropdown-item :icon="Switch">切换账号</el-dropdown-item>
              <el-dropdown-item :icon="SwitchButton">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    
    <div class="hb"></div>
    
    <!-- 主体内容 -->
    <div class="Hbody">
      <!-- 左侧菜单 -->
      <div class="bdl">
        <div class="bdl1">
          <div class="bdl11 noselect xiaoshou" @click="uav" :class="{ 'active-nav': homepage === 2 }">
            <img src="../assets/UAV.png" alt="无人机管理" class="bdl111">
            <div class="bdl112">无人机管理</div>
          </div>
          <div class="bdl12 noselect xiaoshou" @click="mm" :class="{ 'active-nav': homepage === 3 }">
            <img src="../assets/MM.png" alt="商户管理" class="bdl121">
            <div class="bdl122">商户管理</div>
          </div>
          <div class="bdl13 noselect xiaoshou" @click="task" :class="{ 'active-nav': homepage === 4 }">
            <img src="../assets/task.png" alt="任务管理" class="bdl131">
            <div class="bdl132">任务管理</div>
          </div>
          <div class="bdl14 noselect xiaoshou" @click="map" :class="{ 'active-nav': homepage === 5 }">
            <img src="../assets/map.png" alt="地图管理" class="bdl141">
            <div class="bdl142">地图与空域管理</div>
          </div>
          <div class="bdl15 noselect xiaoshou" @click="alarm" :class="{ 'active-nav': homepage === 6 }">
            <img src="../assets/alarm.png" alt="告警中心" class="bdl151">
            <div class="bdl152">告警中心</div>
          </div>
        </div>
      </div>
      
      <!-- 右侧内容区 -->
      <div class="bdr">
        <div class="dashboard-container">
          
          <!-- 筛选栏 -->
          <div class="filter-bar">
            <el-row :gutter="20" class="filter-row">
              <el-col :span="6" :xs="24">
                <el-input 
                  placeholder="搜索商户名称/编号" 
                  v-model="merchantSearchKeyword" 
                  clearable
                  class="search-input"
                >
                  <template #prefix>
                    <Search class="search-icon" />
                  </template>
                </el-input>
              </el-col>
              <el-col :span="4" :xs="12">
                <el-select 
                  v-model="merchantStatusFilter" 
                  placeholder="筛选状态" 
                  clearable
                  class="filter-select"
                >
                  <el-option label="全部" value=""></el-option>
                  <el-option label="活跃" value="active"></el-option>
                  <el-option label="暂停" value="suspended"></el-option>
                  <el-option label="审核中" value="reviewing"></el-option>
                  <el-option label="已禁用" value="disabled"></el-option>
                </el-select>
              </el-col>
              <el-col :span="4" :xs="12">
                <el-select 
                  v-model="merchantTypeFilter" 
                  placeholder="筛选类型" 
                  clearable
                  class="filter-select"
                >
                  <el-option label="全部" value=""></el-option>
                  <el-option label="餐饮" value="food"></el-option>
                  <el-option label="零售" value="retail"></el-option>
                  <el-option label="医药" value="medical"></el-option>
                  <el-option label="其他" value="other"></el-option>
                </el-select>
              </el-col>
              <el-col :span="2" :offset="6" :xs="24" class="add-btn-col">
  <el-button type="primary" @click="addMerchant" class="add-merchant-btn">
    <Plus class="btn-icon" /> 新增商户
  </el-button>
</el-col>
            </el-row>
          </div>

          <!-- 统计卡片 -->
          <div class="dashboard-cards">
            <el-card class="stat-card" shadow="hover" :class="cardHoverClass">
              <template #header>
                <div class="card-header">
                  <span class="card-title">总商户数</span>
                </div>
              </template>
              <div class="card-content">
                <div class="card-value">{{ merchants.length }}</div>
                <div class="card-footer">
                  <span class="card-stat">平台注册商户总数</span>
                </div>
              </div>
            </el-card>
            
            <el-card class="stat-card" shadow="hover" :class="cardHoverClass">
              <template #header>
                <div class="card-header">
                  <span class="card-title">活跃商户</span>
                </div>
              </template>
              <div class="card-content">
                <div class="card-value">{{ activeMerchantCount }}</div>
                <div class="card-progress">
                  <el-progress 
                    :percentage="activeMerchantRate" 
                    color="#67C23A" 
                    stroke-width="6"
                  ></el-progress>
                </div>
                <div class="card-footer">
                  <span class="card-stat">占比 {{ activeMerchantRate }}%</span>
                </div>
              </div>
            </el-card>
            
            <el-card class="stat-card" shadow="hover" :class="cardHoverClass">
              <template #header>
                <div class="card-header">
                  <span class="card-title">今日新增</span>
                </div>
              </template>
              <div class="card-content">
                <div class="card-value">{{ todayNewMerchants }}</div>
                <div class="card-footer">
                  <span class="card-stat">今日新注册商户</span>
                </div>
              </div>
            </el-card>
            
            <el-card class="stat-card" shadow="hover" :class="cardHoverClass">
              <template #header>
                <div class="card-header">
                  <span class="card-title">平均评分</span>
                </div>
              </template>
              <div class="card-content">
                <div class="card-value">{{ averageRating.toFixed(1) }} <Star class="star-icon" /></div>
                <div class="card-footer">
                  <span class="card-stat">基于{{ ratedMerchantCount }}家商户</span>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 商户列表 -->
          <div class="merchant-table-container">
            <el-card class="table-card" shadow="hover">
              <template #header>
                <div class="table-header">
                  <span class="table-title">商户列表</span>
                  <div class="header-actions">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="viewAllMerchants"
                      class="view-all-btn"
                    >
                      查看全部
                    </el-button>
                    <span class="result-count">共 {{ filteredMerchants.length }} 家商户</span>
                  </div>
                </div>
              </template>
              <div class="table-content">
                <!-- 空状态处理 -->
                <div v-if="filteredMerchants.length === 0" class="empty-state">
                  <Empty description="没有找到匹配的商户" />
                  <el-button 
                    type="text" 
                    @click="resetFilters"
                    class="reset-btn"
                  >
                    重置筛选条件
                  </el-button>
                </div>
                
                <!-- 表格内容 -->
                <el-table 
  v-else
  :data="paginatedMerchants" 
  stripe 
  style="width: 100%;"
  @row-click="viewMerchantDetail"
  row-class-name="merchant-row"
  :cell-style="{ padding: '12px 0' }"
>
                  <el-table-column type="index" label="序号" width="60"></el-table-column>
                  <el-table-column prop="id" label="商户编号" width="120"></el-table-column>
                  <el-table-column prop="name" label="商户名称" min-width="150">
                    <template #default="scope">
                      <div class="merchant-name">{{ scope.row.name }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="contactPerson" label="联系人" width="100"></el-table-column>
                  <el-table-column prop="phone" label="联系电话" width="130"></el-table-column>
                  <el-table-column prop="type" label="类型" width="100">
                    <template #default="scope">
                      <el-tag 
                        :type="getMerchantTypeTagType(scope.row.type)"
                        class="type-tag"
                      >
                        {{ getMerchantTypeName(scope.row.type) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                      <el-tag 
                        :type="getMerchantStatusTagType(scope.row.status)"
                        class="status-tag"
                      >
                        {{ getMerchantStatusName(scope.row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="registerTime" label="注册时间" width="130"></el-table-column>
                  <el-table-column prop="rating" label="评分" width="100">
                    <template #default="scope">
                      <div class="rating-star">
                        <span>{{ scope.row.rating.toFixed(1) }} <Star class="star-icon" /></span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="260" fixed="right">
                    <template #default="scope">
                      <el-button 
                        type="text" 
                        size="small" 
                        @click.stop="viewMerchantDetail(scope.row)"
                        class="table-btn view-btn"
                      >
                        详情
                      </el-button>
                      <el-button 
                        type="text" 
                        size="small" 
                        @click.stop="editMerchant(scope.row)"
                        class="table-btn edit-btn"
                      >
                        编辑
                      </el-button>
                      <el-button  
                        size="small" 
                        :type="scope.row.status === 'active' ? 'danger' : 'success'"
                        @click.stop="toggleMerchantStatus(scope.row)"
                        class="table-btn status-btn"
                      >
                        {{ scope.row.status === 'active' ? '禁用' : '启用' }}
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              
              <!-- 分页 -->
              <div class="pagination-container" v-if="filteredMerchants.length > 0">
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="[5, 10, 20, 50]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="filteredMerchants.length"
                  class="pagination"
                ></el-pagination>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>

    <!-- 商户详情弹窗 -->
    <el-dialog 
      v-model="merchantDetailVisible" 
      title="商户详情" 
      :width="800"
      :before-close="handleDialogClose"
      class="detail-dialog"
    >
      <el-row :gutter="20" class="detail-row">
        <el-col :span="6" :xs="24">
          <div class="merchant-photo">
            <img 
              :src="currentMerchant.licensePhoto" 
              alt="营业执照" 
              class="merchant-img"
              @error="handleImgError"
            >
          </div>
          <div class="merchant-status-badge">
            <el-tag 
              :type="getMerchantStatusTagType(currentMerchant.status)"
              size="large"
              class="status-badge"
            >
              {{ getMerchantStatusName(currentMerchant.status) }}
            </el-tag>
          </div>
        </el-col>
        <el-col :span="18" :xs="24">
          <el-descriptions column="1" border class="detail-descriptions">
            <el-descriptions-item label="商户编号">{{ currentMerchant.id }}</el-descriptions-item>
            <el-descriptions-item label="商户名称">{{ currentMerchant.name }}</el-descriptions-item>
            <el-descriptions-item label="商户类型">{{ getMerchantTypeName(currentMerchant.type) }}</el-descriptions-item>
            <el-descriptions-item label="联系人">{{ currentMerchant.contactPerson }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ currentMerchant.phone }}</el-descriptions-item>
            <el-descriptions-item label="详细地址">{{ currentMerchant.address }}</el-descriptions-item>
            <el-descriptions-item label="配送范围">{{ currentMerchant.deliveryRange }} 公里</el-descriptions-item>
            <el-descriptions-item label="注册时间">{{ currentMerchant.registerTime }}</el-descriptions-item>
            <el-descriptions-item label="累计订单">{{ currentMerchant.totalOrders }} 单</el-descriptions-item>
            <el-descriptions-item label="满意度评分">{{ currentMerchant.rating.toFixed(1) }} <Star class="star-icon" /></el-descriptions-item>
            <el-descriptions-item label="备注">{{ currentMerchant.remark || '无' }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
      <template #footer>
        <el-button @click="handleDialogClose">关闭</el-button>
        <el-button type="primary" @click="editMerchant(currentMerchant)">编辑信息</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑商户弹窗 -->
    <el-dialog 
      v-model="merchantFormVisible" 
      :title="isEditMerchant ? '编辑商户' : '新增商户'" 
      :width="600"
      :before-close="handleDialogClose"
      class="form-dialog"
    >
      <el-form 
        :model="merchantForm" 
        label-width="100px" 
        :rules="merchantFormRules"
        ref="merchantFormRef"
        class="merchant-form"
        status-icon
      >
        <el-form-item label="商户名称" prop="name" class="form-item">
          <el-input v-model="merchantForm.name" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="商户类型" prop="type" class="form-item">
          <el-select v-model="merchantForm.type" placeholder="请选择商户类型" class="form-select">
            <el-option label="餐饮" value="food"></el-option>
            <el-option label="零售" value="retail"></el-option>
            <el-option label="医药" value="medical"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson" class="form-item">
          <el-input v-model="merchantForm.contactPerson" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone" class="form-item">
          <el-input v-model="merchantForm.phone" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address" class="form-item">
          <el-input v-model="merchantForm.address" type="textarea" rows="2" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="配送范围(公里)" prop="deliveryRange" class="form-item">
          <el-input 
            v-model.number="merchantForm.deliveryRange" 
            type="number" 
            min="1" 
            max="20"
            class="form-input"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="isEditMerchant" class="form-item">
          <el-select v-model="merchantForm.status" class="form-select">
            <el-option label="活跃" value="active"></el-option>
            <el-option label="暂停" value="suspended"></el-option>
            <el-option label="审核中" value="reviewing"></el-option>
            <el-option label="已禁用" value="disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" class="form-item">
          <el-input 
            v-model="merchantForm.remark" 
            type="textarea" 
            rows="3"
            class="form-input"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelMerchantForm">取消</el-button>
        <el-button type="primary" @click="saveMerchant">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref, computed, onMounted, reactive } from 'vue'
import {
  ArrowDown, Postcard, User, Setting, Switch, SwitchButton,
  Plus, Search, Star, Empty
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 路由相关
const router = useRouter()

// 页面状态
const homepage = ref(3) // 默认显示商户管理页面

// 导航方法
const toHcont = () => {
  homepage.value = 1
  router.push('/HomeViews')
}
const uav = () => { 
  homepage.value = 2
  router.push('/navViews') 
}
const mm = () => { 
  homepage.value = 3
  router.push('/mmViews') 
}
const task = () => { 
  homepage.value = 4 
  router.push('/taskViews')
}
const map = () => { 
  homepage.value = 5
  router.push('/mapViews')
}
const alarm = () => { 
  homepage.value = 6
  router.push('/alarmViews') 
}
const customer = () => { 
  router.push("/chatViews") 
}

// 商户管理相关变量
const merchantSearchKeyword = ref('')
const merchantStatusFilter = ref('')
const merchantTypeFilter = ref('')
const merchantDetailVisible = ref(false)
const merchantFormVisible = ref(false)
const isEditMerchant = ref(false)
const currentMerchant = ref({})
const merchantFormRef = ref(null)

// 分页控制
const currentPage = ref(1)
const pageSize = ref(10)

// 商户表单数据
const merchantForm = reactive({
  id: '',
  name: '',
  type: '',
  contactPerson: '',
  phone: '',
  address: '',
  deliveryRange: 3,
  status: 'reviewing',
  remark: ''
})

// 商户表单验证规则
const merchantFormRules = reactive({
  name: [{ required: true, message: '请输入商户名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择商户类型', trigger: 'change' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  deliveryRange: [
    { required: true, message: '请输入配送范围', trigger: 'blur' },
    { type: 'number', min: 1, max: 20, message: '配送范围应在1-20公里之间', trigger: 'blur' }
  ]
})

// 商户模拟数据
const merchants = ref([
  {
    id: 'MER-001',
    name: '城市咖啡店',
    type: 'food',
    contactPerson: '张三',
    phone: '13800138000',
    address: '科技园区A座101',
    deliveryRange: 3,
    status: 'active',
    registerTime: '2024-01-15',
    totalOrders: 1250,
    rating: 4.8,
    licensePhoto: require('@/assets/coffe.png'),
    remark: '连锁品牌，主打精品咖啡'
  },
  {
    id: 'MER-002',
    name: '鲜果汁吧',
    type: 'food',
    contactPerson: '李四',
    phone: '13900139000',
    address: '商业区B栋203',
    deliveryRange: 2,
    status: 'active',
    registerTime: '2024-02-20',
    totalOrders: 860,
    rating: 4.6,
    licensePhoto: require('@/assets/juce.png'),
    remark: '纯鲜榨果汁，无添加'
  },
  {
    id: 'MER-003',
    name: '便民超市',
    type: 'retail',
    contactPerson: '王五',
    phone: '13700137000',
    address: '居民小区C区底商',
    deliveryRange: 5,
    status: 'suspended',
    registerTime: '2024-03-05',
    totalOrders: 2100,
    rating: 4.2,
    licensePhoto: require('@/assets/super.png'),
    remark: '生活用品齐全，24小时营业'
  },
  {
    id: 'MER-004',
    name: '健康药房',
    type: 'medical',
    contactPerson: '赵六',
    phone: '13600136000',
    address: '医疗园区D座1层',
    deliveryRange: 4,
    status: 'active',
    registerTime: '2024-04-10',
    totalOrders: 580,
    rating: 4.9,
    licensePhoto: require('@/assets/pharmacy.png'),
    remark: '处方药需凭处方购买'
  },
  {
    id: 'MER-005',
    name: '数码配件店',
    type: 'retail',
    contactPerson: '钱七',
    phone: '13500135000',
    address: '电子城E区12号',
    deliveryRange: 3,
    status: 'reviewing',
    registerTime: '2024-07-12',
    totalOrders: 0,
    rating: 0,
    licensePhoto: require('@/assets/data.png'),
    remark: '主营手机配件和小型数码产品'
  },
  {
    id: 'MER-006',
    name: '鲜花礼品店',
    type: 'other',
    contactPerson: '孙八',
    phone: '13400134000',
    address: '步行街F段18号',
    deliveryRange: 6,
    status: 'disabled',
    registerTime: '2024-05-18',
    totalOrders: 320,
    rating: 4.5,
    licensePhoto: require('@/assets/flower.png'),
    remark: '因违规操作被禁用'
  }
])

// 筛选商户列表
const filteredMerchants = computed(() => {
  return merchants.value.filter(merchant => {
    const matchesKeyword = 
      merchant.id.toLowerCase().includes(merchantSearchKeyword.value.toLowerCase()) ||
      merchant.name.toLowerCase().includes(merchantSearchKeyword.value.toLowerCase())
    const matchesStatus = !merchantStatusFilter.value || merchant.status === merchantStatusFilter.value
    const matchesType = !merchantTypeFilter.value || merchant.type === merchantTypeFilter.value
    return matchesKeyword && matchesStatus && matchesType
  }).sort((a, b) => {
    // 按状态优先级排序：活跃 > 审核中 > 暂停 > 禁用
    const statusPriority = { active: 1, reviewing: 2, suspended: 3, disabled: 4 }
    if (statusPriority[a.status] !== statusPriority[b.status]) {
      return statusPriority[a.status] - statusPriority[b.status]
    }
    // 状态相同按注册时间倒序
    return new Date(b.registerTime) - new Date(a.registerTime)
  })
})

// 分页处理
const paginatedMerchants = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  return filteredMerchants.value.slice(startIndex, startIndex + pageSize.value)
})

// 分页方法
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1 // 重置为第一页
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

// 商户统计数据
const activeMerchantCount = computed(() => {
  return merchants.value.filter(m => m.status === 'active').length
})

const activeMerchantRate = computed(() => {
  if (merchants.value.length === 0) return 0
  return Math.round((activeMerchantCount.value / merchants.value.length) * 100)
})

const todayNewMerchants = computed(() => {
  const today = new Date().toISOString().split('T')[0]
  return merchants.value.filter(m => {
    const registerDate = new Date(m.registerTime).toISOString().split('T')[0]
    return registerDate === today
  }).length
})

const averageRating = computed(() => {
  const ratedMerchants = merchants.value.filter(m => m.rating > 0)
  if (ratedMerchants.length === 0) return 0
  const totalRating = ratedMerchants.reduce((sum, m) => sum + m.rating, 0)
  return totalRating / ratedMerchants.length
})

const ratedMerchantCount = computed(() => {
  return merchants.value.filter(m => m.rating > 0).length
})

// 商户类型格式化
const getMerchantTypeName = (type) => {
  const typeMap = {
    food: '餐饮',
    retail: '零售',
    medical: '医药',
    other: '其他'
  }
  return typeMap[type] || type
}

const getMerchantTypeTagType = (type) => {
  const typeMap = {
    food: 'success',
    retail: 'primary',
    medical: 'info',
    other: 'warning'
  }
  return typeMap[type] || 'info'
}

// 商户状态格式化
const getMerchantStatusName = (status) => {
  const statusMap = {
    active: '活跃',
    suspended: '暂停',
    reviewing: '审核中',
    disabled: '已禁用'
  }
  return statusMap[status] || status
}

const getMerchantStatusTagType = (status) => {
  const typeMap = {
    active: 'success',
    suspended: 'warning',
    reviewing: 'info',
    disabled: 'danger'
  }
  return typeMap[status] || 'info'
}

// 商户操作方法
const viewMerchantDetail = (merchant) => {
  currentMerchant.value = { ...merchant }
  merchantDetailVisible.value = true
}

const addMerchant = () => {
  isEditMerchant.value = false
  // 重置表单
  Object.assign(merchantForm, {
    id: `MER-${(merchants.value.length + 1).toString().padStart(3, '0')}`,
    name: '',
    type: '',
    contactPerson: '',
    phone: '',
    address: '',
    deliveryRange: 3,
    status: 'reviewing',
    remark: ''
  })
  merchantFormVisible.value = true
}

const editMerchant = (merchant) => {
  isEditMerchant.value = true
  currentMerchant.value = { ...merchant }
  // 填充表单
  Object.assign(merchantForm, { ...merchant })
  merchantFormVisible.value = true
}

const toggleMerchantStatus = (merchant) => {
  const newStatus = merchant.status === 'active' ? 'disabled' : 'active'
  const actionText = newStatus === 'active' ? '启用' : '禁用'
  
  ElMessageBox.confirm(
    `确定要${actionText}商户「${merchant.name}」吗？`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: newStatus === 'active' ? 'success' : 'warning',
    }
  )
  .then(() => {
    const index = merchants.value.findIndex(m => m.id === merchant.id)
    if (index !== -1) {
      merchants.value[index].status = newStatus
      ElMessage.success(`已${actionText}商户：${merchant.name}`)
    }
  })
  .catch(() => {
    // 取消操作
  })
}

const saveMerchant = () => {
  // 表单验证
  merchantFormRef.value.validate((valid) => {
    if (valid) {
      if (isEditMerchant.value) {
        // 编辑现有商户
        const index = merchants.value.findIndex(m => m.id === merchantForm.id)
        if (index !== -1) {
          merchants.value[index] = { ...merchantForm }
          ElMessage.success('商户信息已更新')
        }
      } else {
        // 新增商户
        const newMerchant = {
          ...merchantForm,
          registerTime: new Date().toISOString().split('T')[0],
          totalOrders: 0,
          rating: 0,
          licensePhoto: require('@/assets/arrow.png')
        }
        merchants.value.push(newMerchant)
        ElMessage.success('新增商户成功，等待审核')
      }
      merchantFormVisible.value = false
    }
  })
}

const cancelMerchantForm = () => {
  merchantFormRef.value.resetFields()
  merchantFormVisible.value = false
}

const viewAllMerchants = () => {
  resetFilters()
}

const resetFilters = () => {
  merchantSearchKeyword.value = ''
  merchantStatusFilter.value = ''
  merchantTypeFilter.value = ''
  currentPage.value = 1
}

// 弹窗关闭处理
const handleDialogClose = () => {
  merchantDetailVisible.value = false
  merchantFormVisible.value = false
}

// 图片加载失败处理
const handleImgError = (e) => {
  e.target.src = require('@/assets/arrow.png') // 替换为默认图片
}

// 卡片hover样式
const cardHoverClass = ref('card-hover')

onMounted(() => {
  // 组件挂载时的初始化操作
})
</script>

<style scoped>
/* 基础样式 */
.Hcont{
  border-radius: 20px;
  display: flex;
  flex-direction: column;
  width: 97vw;
  height: 98vh;
  overflow: hidden;
  background-color: rgb(239, 239, 238);
}

.Hhead{
  height: 100px;
  width: 100%;
  background-color: rgb(86, 119, 231);
  display: flex;
  flex: none;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.hd1{
  display: flex;
  margin-left: 60px;
}

.hd11{
  width: 60px;
  border-radius: 100%;
  margin-right: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.hd12{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.hd121{
  font-size: 24px;
  font-weight: 500;
  letter-spacing: 3px;
  color: white;
}

.hd122{
  font-size: 12px;
  color: white;
}

.hd2{
  margin-left: 100px;
  width: 70px;
  margin-top: 30px;
}

.hd3{
  margin-right: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.hd31{
  width: 50px;
  border-radius: 100%;
  margin-right: 10px;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.el-dropdown-link{
  color: white;
  outline: none;
  display: flex;
  align-items: center;
}

.hd4{
  flex: 1;
}

.hb{
  width: 100%;
  height: 1px;
  flex: none;
  background-color: #e5e7eb;
}

.Hbody{
  display: flex;
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.bdl{
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 280px;
  background-color: rgb(30, 58, 138);
  transition: width 0.3s ease;
}

.bdl1{
  display: flex;
  flex-direction: column;
  width: 100%;
  align-items: center;
  margin-top: 50px;
}

.bdl11,.bdl12,.bdl13,.bdl14,.bdl15{
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.bdl11:hover,.bdl12:hover,.bdl13:hover,.bdl14:hover,.bdl15:hover{
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px); 
  background-color: rgb(156, 188, 249);
  border-radius: 10px;
}

.bdl11:active,.bdl12:active,.bdl13:active,.bdl14:active,.bdl15:active{
  transform: scale(0.97);
  box-shadow: 0 4px 6px -1px rgba(93, 102, 122, 0.1);
}

.bdl111,.bdl121,.bdl131,.bdl141,.bdl151{
  width: 20px;
  padding-right: 10px;
}

.bdl112,.bdl122,.bdl132,.bdl142,.bdl152{
  font-size: 24px;
  font-weight: 400;
  color: white;
}

.active-nav {
  background-color: rgb(156, 188, 249);
  border-radius: 10px;
}

.bdr {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 25px;
}



/* 筛选栏样式 */
.filter-bar {
  background-color: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.filter-row {
  width: 100%;
}

.search-input {
  width: 100%;
  transition: all 0.3s ease;
}

.search-input:focus-within {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.search-icon {
  color: #c0c4cc;
}

.filter-select {
  width: 100%;
}

.add-btn-col {
  display: flex;
  justify-content: flex-end;
}

.add-merchant-btn {
  width: 100%;
  transition: all 0.2s ease;
}

.add-merchant-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.btn-icon {
  margin-right: 5px;
}

/* 统计卡片样式 */
.dashboard-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 25px;
}

.stat-card {
  height: 180px;
  min-width: 200px;
  transition: all 0.3s ease;
  border-radius: 8px;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.card-title {
  font-size: 16px;
  color: #606266;
  font-weight: 500;
}

.card-content {
  display: flex;
  flex-direction: column;
  height: calc(100% - 40px);
  justify-content: space-between;
  padding-top: 15px;
}

.card-value {
  font-size: 36px;
  font-weight: 500;
  margin: -15px 0 10px 0; 
  color: #1f2329;
  line-height: 1;
}

.star-icon {
  color: #E6A23C;
  width: 50px;
  vertical-align: middle;
}

.card-progress {
  margin-bottom: 10px;
}

.card-footer {
  color: #909399;
  font-size: 14px;
}

/* 表格容器样式 */
.merchant-table-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: none;
  border-radius: 8px;
}

.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.table-title {
  font-size: 16px;
  font-weight: 500;
  color: #1f2329;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.view-all-btn {
  padding: 5px 15px;
}

.result-count {
  color: #606266;
  font-size: 14px;
}

.table-content {
  flex: 1;
  padding-top: 15px;
  overflow: auto;
}

/* 表格样式 */
.merchant-row {
  transition: background-color 0.2s ease;
}

.merchant-row:hover > td {
  background-color: #f5f7fa !important;
}

.table-btn {
  padding: 5px 10px;
  margin-right: 5px;
  transition: all 0.2s ease;
}

.view-btn {
  color: #409EFF;
}

.edit-btn {
  color: #67C23A;
}

.status-btn {
  padding: 5px 10px;
}

.merchant-name {
  font-weight: 500;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #909399;
}

.reset-btn {
  margin-top: 15px;
  color: #409EFF;
}

/* 详情弹窗样式 */
.detail-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.detail-row {
  margin-bottom: 10px;
}

.merchant-photo {
  display: flex;
  justify-content: center;
  padding: 10px;
}

.merchant-img {
  width: 100%;
  max-width: 180px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  object-fit: cover;
  height: 200px;
  transition: all 0.3s ease;
}

.merchant-img:hover {
  transform: scale(1.03);
}

.merchant-status-badge {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}

.status-badge {
  width: 80%;
}

.detail-descriptions {
  margin-top: 10px;
}

.el-descriptions__label {
  font-weight: 500 !important;
  background-color: #f5f7fa !important;
}

/* 表单弹窗样式 */
.form-dialog {
  border-radius: 8px;
}

.merchant-form {
  margin-top: 10px;
}

.form-item {
  margin-bottom: 15px;
}

.form-input, .form-select {
  width: 100%;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .dashboard-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .dashboard-cards {
    grid-template-columns: 1fr;
  }
  
  .bdl {
    width: 60px;
  }
  
  .bdl112, .bdl122, .bdl132, .bdl142, .bdl152 {
    display: none;
  }
  
  .hd1 {
    margin-left: 20px;
  }
  
  .hd2 {
    margin-left: 20px;
  }
  
  .hd3 {
    margin-right: 20px;
  }
  
  .bdr {
    padding: 10px;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.stat-card, .filter-bar, .table-card {
  animation: fadeIn 0.5s ease forwards;
}

.stat-card:nth-child(1) { animation-delay: 0.1s; }
.stat-card:nth-child(2) { animation-delay: 0.2s; }
.stat-card:nth-child(3) { animation-delay: 0.3s; }
.stat-card:nth-child(4) { animation-delay: 0.4s; }
</style>